package com.mobile.challenge.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.textfield.TextInputLayout;
import com.king.base.util.SharedPreferencesUtils;
import com.mobile.challenge.R;
import com.mobile.challenge.bean.UserBean;
import com.mobile.challenge.databinding.FragmentResetPasswordBinding;
import com.mobile.challenge.fingerprint.KeyHelper;
import com.mobile.challenge.user.UserHelper;
import com.mobile.challenge.util.RestartTools;
import com.mobile.challenge.widget.PasswordEditText;
import com.mobile.frame.mvvmframe.base.BaseFragment;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import static com.mobile.challenge.util.ConstantsKt.PASSWORD;


public class ResetPasswordFragment extends BaseFragment<ResetPasswordViewModel, FragmentResetPasswordBinding> {

    private View view;
    private PasswordEditText passwordEditText_new;
    private PasswordEditText passwordEditText_old;
    private TextInputLayout mTextInputLayout;
    private TextView submitBtn;
    private TextInputLayout mTextInputLayout2;

    public static ResetPasswordFragment getInstance() {
        ResetPasswordFragment resetPasswordFragment = new ResetPasswordFragment();
        return resetPasswordFragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_reset_password;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //  自动生成的返回键处理  结合 onOptionsItemSelected
        setHasOptionsMenu(true);
        initView();

//        ((DashboardActivity)requireActivity()).getto().setna

        requireActivity().getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment);
                navController.popBackStack();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case android.R.id.home:
                // 处理返回逻辑
                NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment);
                navController.popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initView() {
        passwordEditText_new = (PasswordEditText) mBinding.getRoot().findViewById(R.id.new_password_et);
        passwordEditText_old = (PasswordEditText) mBinding.getRoot().findViewById(R.id.old_password_et);
        mTextInputLayout = (TextInputLayout) mBinding.getRoot().findViewById(R.id.layout);
        mTextInputLayout2 = (TextInputLayout) mBinding.getRoot().findViewById(R.id.layout2);
        submitBtn = (TextView) mBinding.getRoot().findViewById(R.id.submit_btn);
        submitBtn.setEnabled(true);
//        passwordEditText_new.addTextChangedListener();

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String oldPassword = passwordEditText_old.getText().toString();
                String newPassword = passwordEditText_new.getText().toString();
                if (TextUtils.isEmpty(oldPassword)) {
                    Toast.makeText(requireContext(), "Error: old password is empty!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(newPassword)) {
                    Toast.makeText(requireContext(), "Error: new password is empty!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (newPassword.length() < 6) {
                    Toast.makeText(requireContext(), "Error: new password is too short!", Toast.LENGTH_SHORT).show();
                    return;
                }
                mViewModel.reset(
                        UserHelper.Companion.getInstance().getUserName(),
                        oldPassword,
                        newPassword
                );

                mViewModel.getResetData().observe(getViewLifecycleOwner(), userBean ->
                        savePassword(userBean));
                new AlertDialog.Builder(requireContext())
                        .setTitle("Success")
                        .setMessage("Reset password success, please login again")
                        .setCancelable(false)
                        .setPositiveButton("Sure", (dialog, which) -> {
                            restartApp();
                        })
                        .show();

                mViewModel.getResetError().observe(getViewLifecycleOwner(), e ->
                        Toast.makeText(requireContext(), "reset password error, please try it again later.", Toast.LENGTH_SHORT).show()
                );
            }
        });
    }

    private void savePassword(UserBean userBean) {
        try {
            KeyHelper keyHelper = KeyHelper.getInstance(requireActivity());
            SharedPreferencesUtils.put(requireActivity(), PASSWORD, keyHelper.encrypt(requireActivity(), userBean.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void restartApp() {
        RestartTools.restartApp(requireActivity());
    }


}